package com.baize.channel.game;

import android.annotation.SuppressLint;
import android.app.Activity;
import android.app.AlertDialog;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.net.http.SslError;
import android.os.Build;
import android.os.Bundle;
import android.os.Handler;
import android.text.TextUtils;
import android.util.Log;
import android.view.View;
import android.view.Window;
import android.view.WindowManager;
import android.webkit.JavascriptInterface;
import android.webkit.SslErrorHandler;
import android.webkit.WebChromeClient;
import android.webkit.WebResourceResponse;
import android.webkit.WebSettings;
import android.webkit.WebView;
import android.webkit.WebViewClient;
import android.widget.ImageView;
import android.widget.ProgressBar;
import android.widget.Toast;

import com.baize.channel.game.util.AppConfig;
import com.baize.channel.game.util.CommonUtil;
import com.baize.channel.game.util.Constant;
import com.baize.channel.game.util.RomUtil;
import com.baize.channel.game.view.GameWebView;
import com.baizesdk.sdk.BZCode;
import com.baizesdk.sdk.BZSDK;
import com.baizesdk.sdk.DefaultBZSDKListener;
import com.baizesdk.sdk.InitResult;
import com.baizesdk.sdk.PayResult;
import com.baizesdk.sdk.bean.Constants;
import com.baizesdk.sdk.bean.GameRoleInfo;
import com.baizesdk.sdk.bean.PayParams;
import com.baizesdk.sdk.bean.UToken;
import com.baizesdk.sdk.bean.UserExtraData;
import com.baizesdk.sdk.plugin.BZPay;
import com.baizesdk.sdk.plugin.BZUser;

import java.io.IOException;
import java.math.BigDecimal;
import java.util.HashMap;
import java.util.concurrent.CountDownLatch;
import org.json.JSONException;
import org.json.JSONObject;

public class GameActivity extends Activity {
    private static final int PERMISSIONS_REQUEST_ID = 9999;
    private static final String REQ_CANCEL = "cancel";
    private static final String REQ_FAILED = "failed";
    private static final String TAG = "jsShell.ma";
    private static CountDownLatch countDown = new CountDownLatch(1);
    private HashMap<String, String> cachedFilesJs = new HashMap<>();
    private JSONObject dataJsonObject = new JSONObject();
    private boolean hasNeedPermissions;
    private Activity mActivity = null;
    private ProgressBar mBar;
    private GameWebView mGameWebView;
    private Boolean mInitFinished = false;
    private Boolean mIniting = false;
    private Boolean mNeedRetryLogin = false;
    private ImageView mSplashImageView;
    private String mUrl;
    private String mainJSKey = "bzsdk.min.js";
    private String mainJSUrl = "libBZHDSDKH5_To_Client.js";
    private boolean showBar = true;

    @Override // android.app.Activity
    public void onCreate(Bundle savedInstanceState) {
        Log.d(TAG, "requestWindowFeature(Window.FEATURE_NO_TITLE)");
        requestWindowFeature(1);
        super.onCreate(savedInstanceState);
        Log.d(TAG, "onCreate");
        BZSDK.getInstance().onCreate(this);
        getWindow().addFlags(128);
        this.mActivity = this;
        this.cachedFilesJs.put(this.mainJSKey, this.mainJSUrl);
        getWindow().setFlags(1024, 1024);
        changeScreen();
        setHideVirtualKey(getWindow());
        setContentView(getResourceId("game_activity", "layout"));
        this.mSplashImageView = (ImageView) findViewById(getResourceId("iv_last_splash", "id"));
        this.mSplashImageView.setBackgroundResource(getIntent().getIntExtra("id", getResources().getIdentifier("b_splash_img_0", "drawable", getPackageName())));
        this.mBar = (ProgressBar) findViewById(getResourceId("myProgressBar", "id"));
        AppConfig.init(getAssets());
        this.mUrl = AppConfig.gameUrl;
        Log.d(TAG, "onCreate url:" + this.mUrl);
        if (TextUtils.isEmpty(this.mUrl)) {
            Toast.makeText(this, "H5游戏的url为空，请配置", Toast.LENGTH_LONG).show();
            return;
        }
        setNotifiers();
        if (judgeRequestPermissions()) {
            Log.d(TAG, "init"+AppConfig.appid);
            BZSDK.getInstance().init(this,AppConfig.appid,AppConfig.appkey);
        }
        initWebViews();
        getWindow().getDecorView().setOnSystemUiVisibilityChangeListener(new View.OnSystemUiVisibilityChangeListener() {
            /* class com.qk.plugin.js.shell.MainActivity.AnonymousClass1 */

            @Override // android.view.View.OnSystemUiVisibilityChangeListener
            public void onSystemUiVisibilityChange(int visibility) {
                GameActivity.this.setHideVirtualKey(GameActivity.this.getWindow());
            }
        });
    }

    private void changeScreen() {
        if (Build.VERSION.SDK_INT >= 28) {
            WindowManager.LayoutParams lp = getWindow().getAttributes();
            lp.layoutInDisplayCutoutMode = 1;
            getWindow().setAttributes(lp);
        }
    }

    private void doRequestPermissionsWork() {
        try {
            if (judgeRequestPermissions()) {
                Log.d(TAG, "ContextCompat.checkSelfPermission passed");
                grantPermissions();
                init();
                return;
            }
            Log.d(TAG, " onCreate ActivityCompat.requestPermissions");
            if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) {
                requestPermissions(new String[]{"android.permission.READ_PHONE_STATE", "android.permission.WRITE_EXTERNAL_STORAGE"}, PERMISSIONS_REQUEST_ID);
            }
        } catch (Exception e) {
            Log.d(TAG, "ContextCompat.checkSelfPermission Exception e:" + e.getMessage());
            grantPermissions();
            init();
        }
    }

    private boolean judgeRequestPermissions() {
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) {
            int checkReadPhonePermission = checkSelfPermission("android.permission.READ_PHONE_STATE");
            int checkWritePermission = checkSelfPermission("android.permission.WRITE_EXTERNAL_STORAGE");
            Log.d(TAG, "checkReadPhonePermission:" + checkReadPhonePermission);
            Log.d(TAG, "checkWritePermission:" + checkWritePermission);
            if (checkReadPhonePermission == 0 && checkWritePermission == 0) {
                return true;
            }
            return false;
        }
        return true;
    }

    private void grantPermissions() {
        Log.d(TAG, "grantPermissions()");
        this.hasNeedPermissions = true;
    }

    private boolean judgeRequestPermissions(String[] permissions, int[] grantResults) {
        boolean flag = true;
        Log.d(TAG, " judgeRequestPermissions grantResults:" + grantResults);
        if (grantResults != null) {
            for (int i : grantResults) {
                if (i != 0) {
                    flag = false;
                }
            }
        }
        return flag;
    }

    @Override // android.app.Activity
    public void onRequestPermissionsResult(int requestCode, String[] permissions, int[] grantResults) {
        Log.d(TAG, " onRequestPermissionsResult requestCode:" + requestCode);
        try {
            boolean flag = judgeRequestPermissions(permissions, grantResults);
            Log.d(TAG, " onRequestPermissionsResult flag:" + flag);
            if (flag) {
                grantPermissions();
                init();
            } else if (getApplicationInfo().targetSdkVersion < 23) {
                Log.d(TAG, " onRequestPermissionsResult getApplicationInfo().targetSdkVersion");
                grantPermissions();
                init();
            } else {
                Log.d(TAG, " onRequestPermissionsResult ActivityCompat.requestPermissions");
                if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) {
                    requestPermissions( new String[]{"android.permission.READ_PHONE_STATE", "android.permission.WRITE_EXTERNAL_STORAGE"}, PERMISSIONS_REQUEST_ID);
                }
            }
        } catch (Exception e) {
            Log.d(TAG, " onRequestPermissionsResult Erro: " + e.toString());
            grantPermissions();
            init();
        }
    }

    @SuppressLint({"SetJavaScriptEnabled"})
    private void initWebViews() {
        Log.d(TAG, "initWebViews");
        this.mGameWebView = (GameWebView) findViewById(getResourceId("wb_main_game", "id"));
        this.mGameWebView.setWebViewClient(new WebViewClient() {

            @Override
            public boolean shouldOverrideUrlLoading(WebView view, String url) {
                Log.d(GameActivity.TAG, "initWebViews shouldOverrideUrlLoading loadUrl");
                view.loadUrl(url);
                return true;
            }

            @Override
            public void onReceivedSslError(WebView view, SslErrorHandler handler, SslError error) {
                if (GameActivity.this.mUrl.startsWith("http")) {
                    Log.e(GameActivity.TAG, "证书认证失败，依然接受证书");
                    handler.proceed();
                }
            }

            @Override
            public void onPageFinished(WebView arg0, String arg1) {
                new Handler().postDelayed(new Runnable() {

                    @Override // java.lang.Runnable
                    public void run() {
                        GameActivity.this.mBar.setVisibility(View.GONE);
                        GameActivity.this.mSplashImageView.setVisibility(View.GONE);
                    }
                }, 1200);
                if (!GameActivity.this.judgeRequestPermissions()) {
                    new Handler().postDelayed(new Runnable() {

                        @Override // java.lang.Runnable
                        public void run() {
                            GameActivity.this.doRequestPermissionsWork();
                        }
                    }, 1500);
                }
            }

            @Override
            public WebResourceResponse shouldInterceptRequest(WebView view, String url) {
                Log.d(GameActivity.TAG, "shouldInterceptRequest  ：" + url);
                if (url.contains("bzsdk.min.js")) {
                    try {
                        Log.d(GameActivity.TAG, "LoadFromLocal:" + GameActivity.this.getBaseContext().getAssets().open((String) GameActivity.this.cachedFilesJs.get(GameActivity.this.mainJSKey)) + ":" + Thread.currentThread());
                        return new WebResourceResponse("application/x-javascript", "utf-8", GameActivity.this.getBaseContext().getAssets().open((String) GameActivity.this.cachedFilesJs.get(GameActivity.this.mainJSKey)));
                    } catch (IOException e) {
                        Log.d(GameActivity.TAG, "LoadFromLocal  IOException:" + e.toString());
                        e.printStackTrace();
                    }
                }
                return super.shouldInterceptRequest(view, url);
            }
        });
        this.mGameWebView.getSettings().setUserAgentString("QuickBrowserAndroid");
        this.mGameWebView.getSettings().setCacheMode(WebSettings.LOAD_DEFAULT);
        this.mGameWebView.getSettings().setJavaScriptEnabled(true);
        this.mGameWebView.getSettings().setDomStorageEnabled(true);
        this.mGameWebView.getSettings().setDatabaseEnabled(true);
        this.mGameWebView.getSettings().setAppCachePath(getApplicationContext().getCacheDir().getAbsolutePath());
        this.mGameWebView.getSettings().setAppCacheEnabled(true);
        this.mGameWebView.getSettings().setAllowFileAccess(true);
        this.mGameWebView.getSettings().setSupportZoom(true);
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.JELLY_BEAN) {
            this.mGameWebView.getSettings().setAllowFileAccessFromFileURLs(true);
        }
        this.mGameWebView.getSettings().setBuiltInZoomControls(true);
        if (17 <= Build.VERSION.SDK_INT) {
            this.mGameWebView.getSettings().setMediaPlaybackRequiresUserGesture(false);
        }
        this.mGameWebView.addJavascriptInterface(new BZHDJsInterface(), "JObject");
        this.mGameWebView.setWebChromeClient(new WebChromeClient() {

            @Override // android.webkit.WebChromeClient
            public void onProgressChanged(WebView view, int newProgress) {
                if (GameActivity.this.showBar) {
                    GameActivity.this.showBar = false;
                    GameActivity.this.mBar.setVisibility(View.VISIBLE);
                }
                Log.d(GameActivity.TAG, "newProgress========" + newProgress);
                GameActivity.this.mBar.setProgress(newProgress);
                super.onProgressChanged(view, newProgress);
            }
        });
        this.mGameWebView.loadUrl(this.mUrl);
    }

    private int getResourceId(String name, String defType) {
        return getResources().getIdentifier(name, defType, getPackageName());
    }


    @Override
    public void onStart() {
        Log.d(TAG, "onStart");
        super.onStart();
        BZSDK.getInstance().onStart(this);
    }

    @Override
    public void onRestart() {
        Log.d(TAG, "onRestart");
        super.onRestart();
        BZSDK.getInstance().onRestart(this);
    }

    @Override
    public void onPause() {
        Log.d(TAG, "onPause");
        super.onPause();
        BZSDK.getInstance().onPause(this);
        if (this.mGameWebView != null) {
            this.mGameWebView.onPause();
        }
    }

    @Override // android.app.Activity
    public void onResume() {
        Log.d(TAG, "onResume");
        super.onResume();
        JSONObject jsonObject = new JSONObject();
        try {
            jsonObject.put("action", "onResume");
            jsonObject.put("data", new JSONObject());
        } catch (JSONException e) {
            CommonUtil.printThrowableInfo(e);
        }
        callJsFunc(jsonObject);
        BZSDK.getInstance().onResume(this);
        if (this.mGameWebView != null) {
            this.mGameWebView.onResume();
        }
    }

    @Override // android.app.Activity
    public void onStop() {
        Log.d(TAG, "onStop");
        super.onStop();
        JSONObject jsonObject = new JSONObject();
        try {
            jsonObject.put("action", "onStop");
            jsonObject.put("data", new JSONObject());
        } catch (JSONException e) {
            CommonUtil.printThrowableInfo(e);
        }
        callJsFunc(jsonObject);
        BZSDK.getInstance().onStop(this);
    }

    @Override // android.app.Activity
    public void onDestroy() {
        Log.d(TAG, "onDestroy");
        super.onDestroy();
        BZSDK.getInstance().onDestroy(this);
    }

    @Override // android.app.Activity
    public void onNewIntent(Intent intent) {
        Log.d(TAG, "onNewIntent");
        super.onNewIntent(intent);
        BZSDK.getInstance().onNewIntent(intent);
    }

    @Override // android.app.Activity
    public void onActivityResult(int requestCode, int resultCode, Intent data) {
        Log.d(TAG, "onActivityResult");
        super.onActivityResult(requestCode, resultCode, data);
        BZSDK.getInstance().onActivityResult(this, requestCode, resultCode, data);
    }

    private void setNotifiers() {
        Log.d(TAG, "setNotifiers");
        BZSDK.getInstance().setSDKListener(new DefaultBZSDKListener() {
            @Override
            public void onInitResult(InitResult result) {
                int code = result.getCode();
                String ext = result.getExtension();//渠道扩展参数;
                switch(code){
                    case BZCode.CODE_INIT_SUCCESS:
                        if (GameActivity.this.mNeedRetryLogin.booleanValue()) {
                            Log.d(GameActivity.TAG, "init success...retry login");
                            GameActivity.this.mNeedRetryLogin = false;
                            GameActivity.this.login();
                        }
                        GameActivity.this.mIniting = false;
                        GameActivity.this.mInitFinished = true;
                        break;
                    case BZCode.CODE_INIT_FAIL:
                        Log.d(GameActivity.TAG, "init failed msg:" + ext );
                        if (GameActivity.this.mNeedRetryLogin.booleanValue()) {
                            Log.d(GameActivity.TAG, "init failed...retry login");
                            GameActivity.this.mNeedRetryLogin = false;
                            GameActivity.this.login();
                        }
                        GameActivity.this.mIniting = false;
                        GameActivity.this.mInitFinished = true;
                        break;
                }
            }

            @Override
            public void onSwitchAccount(int code, UToken token) {
                Log.d(GameActivity.TAG, "switch account success");
                JSONObject jsonObject = new JSONObject();
                try {
                    jsonObject.put("action", "switchAccountNotify");
                    JSONObject dataJsonObject = new JSONObject();
                    dataJsonObject.put("status", true);
                    dataJsonObject.put("userId", token.getUserID());
                    dataJsonObject.put("username", token.getUsername());
                    dataJsonObject.put("token", token.getToken());
                    jsonObject.put("data", dataJsonObject);
                } catch (JSONException e) {
                    CommonUtil.printThrowableInfo(e);
                }
                GameActivity.this.callJsFunc(jsonObject);
            }

            public void onLoginResult(int code, UToken token) {
                JSONObject jsonObject = new JSONObject();
                switch(code){
                    case BZCode.CODE_LOGIN_SUCCESS:
                        Log.d(GameActivity.TAG, "login success");
                        GameActivity.this.mNeedRetryLogin = false;
                        try {
                            jsonObject.put("action", "loginNotify");
                            JSONObject dataJsonObject = new JSONObject();
                            dataJsonObject.put("status", true);
                            dataJsonObject.put("userId", token.getUserID());
                            dataJsonObject.put("userName", token.getUsername());
                            dataJsonObject.put("token", token.getToken());
                            jsonObject.put("data", dataJsonObject);
                        } catch (JSONException e) {
                            CommonUtil.printThrowableInfo(e);
                        }
                        GameActivity.this.callJsFunc(jsonObject);
                        break;
                    case BZCode.CODE_LOGIN_FAIL:
                        Log.d(GameActivity.TAG, "login failed ");
                        GameActivity.this.mNeedRetryLogin = false;
                        try {
                            jsonObject.put("action", "loginNotify");
                            JSONObject dataJsonObject = new JSONObject();
                            dataJsonObject.put("status", false);
                            dataJsonObject.put("status_key", GameActivity.REQ_FAILED);
                            dataJsonObject.put("message", "fail");
                            jsonObject.put("data", dataJsonObject);
                        } catch (JSONException e) {
                            CommonUtil.printThrowableInfo(e);
                        }
                        GameActivity.this.callJsFunc(jsonObject);
                        break;
                }
            }

            @Override
            public void onLogout() {
//                Log.d(GameActivity.TAG, "lgout success");
//                JSONObject jsonObject = new JSONObject();
//                try {
//                    jsonObject.put("action", "logoutNotify");
//                    JSONObject dataJsonObject = new JSONObject();
//                    dataJsonObject.put("status", true);
//                    jsonObject.put("data", dataJsonObject);
//                } catch (JSONException e) {
//                    CommonUtil.printThrowableInfo(e);
//                }
//                GameActivity.this.callJsFunc(jsonObject);
                mGameWebView.loadUrl(mUrl);
            }

            @Override
            public void onPayResult(PayResult result) {
               try{
                   JSONObject jsonObject = new JSONObject();
                   JSONObject dataJsonObject = new JSONObject();
                   dataJsonObject.put("productID",result.getProductID());
                   dataJsonObject.put("productName",result.getProductName());
                   dataJsonObject.put("extension",result.getExtension());

                   jsonObject.put("action", "payNotify");
                   dataJsonObject.put("status", true);
                   jsonObject.put("data", dataJsonObject);
                   GameActivity.this.callJsFunc(jsonObject);
               }catch (Exception e){

               }
            }

            @Override
            public void onGameExit() {
                Log.d(GameActivity.TAG, "exit success");
                JSONObject jsonObject = new JSONObject();
                try {
                    jsonObject.put("action", "exitNotify");
                    JSONObject dataJsonObject = new JSONObject();
                    dataJsonObject.put("status", true);
                    jsonObject.put("data", dataJsonObject);
                } catch (JSONException e) {
                    CommonUtil.printThrowableInfo(e);
                }
                GameActivity.this.callJsFunc(jsonObject);
                GameActivity.this.finish();
                System.exit(0);
            }

        });

    }

    private void doBZHDSDKinit() {
        Log.d(TAG, "hasNeedPermissions=========" + this.hasNeedPermissions);
        if (!judgeRequestPermissions()) {
            this.hasNeedPermissions = false;
        }
        if (this.hasNeedPermissions) {
            runOnUiThread(new Runnable() {
                /* class com.qk.plugin.js.shell.MainActivity.AnonymousClass10 */

                @Override // java.lang.Runnable
                public void run() {
                    Log.d(GameActivity.TAG, "do init");
                    BZSDK.getInstance().init(GameActivity.this, AppConfig.appid, AppConfig.appkey);
                }
            });
        }
    }

    public void init() {
        try {
            Log.d(TAG, "init before judge hasNeedPermissions");
            Log.d(TAG, "hasNeedPermissions=========" + this.hasNeedPermissions);
            Log.d(TAG, "init");
            if (!this.mInitFinished.booleanValue()) {
                if (!this.mIniting.booleanValue()) {
                    this.mIniting = true;
                    doBZHDSDKinit();
                    return;
                }
                doBZHDSDKinit();
            }
        } catch (Exception e) {
            this.mIniting = false;
            this.mInitFinished = false;
            CommonUtil.printThrowableInfo(e);
        }
    }

    public void login() {
        try {
            BZSDK.getInstance().runOnMainThread(new Runnable() {
                @Override
                public void run() {
                    new Runnable() {
                        /* class com.qk.plugin.js.shell.MainActivity.AnonymousClass11 */

                        @Override // java.lang.Runnable
                        public void run() {
                            Log.d(GameActivity.TAG, "do login================>>>>>>>>>>>");
                            BZUser.getInstance().login(GameActivity.this);
                        }
                    };
                }
            });
        } catch (Exception e) {
            CommonUtil.printThrowableInfo(e);
        }
    }

    public void logout() {
        try {
            runOnUiThread(new Runnable() {
                /* class com.qk.plugin.js.shell.MainActivity.AnonymousClass12 */

                @Override // java.lang.Runnable
                public void run() {
                    Log.d(GameActivity.TAG, "do logout");
                    BZUser.getInstance().logout(GameActivity.this);
                }
            });
        } catch (Exception e) {
            CommonUtil.printThrowableInfo(e);
        }
    }

    public void setGameRoleInfo(final JSONObject jsonObject) {
        try {
            runOnUiThread(new Runnable() {
                /* class com.qk.plugin.js.shell.MainActivity.AnonymousClass13 */

                @Override // java.lang.Runnable
                public void run() {
                    Log.d(GameActivity.TAG, "do setGameRoleInfo");
                    GameActivity.this.bzSetGameRoleInfo(
                            jsonObject.optString("serverId"),
                            jsonObject.optString("serverName"),
                            jsonObject.optString("roleId"),
                            jsonObject.optString("roleName"),
                            jsonObject.optString("roleLevel"),
                            jsonObject.optString("vipLevel"),
                            jsonObject.optString("amount"),
                            jsonObject.optString("partyName"),
                            jsonObject.optString("partyId"),
                            jsonObject.optString("roleGender"),
                            jsonObject.optString("rolePower"),
                            jsonObject.optString("partyRoleId"),
                            jsonObject.optString("partyRoleName"),
                            jsonObject.optString("professionId"),
                            jsonObject.optString("professionName"));
                }
            });
        } catch (Exception e) {
            CommonUtil.printThrowableInfo(e);
        }
    }

    public void pay(final JSONObject orderInfoObj) {
        try {

            runOnUiThread(new Runnable() {
                /* class com.qk.plugin.js.shell.MainActivity.AnonymousClass14 */

                @Override // java.lang.Runnable
                public void run() {
                    GameRoleInfo roleInfo = new GameRoleInfo();
                    PayParams orderInfo =null;
                    try {
                        roleInfo.setServerId(orderInfoObj.getString("serverId"));
                        roleInfo.setServerName(orderInfoObj.getString("serverName"));
                        roleInfo.setRoleId(orderInfoObj.getString("roleId"));
                        roleInfo.setRoleName(orderInfoObj.getString("roleName"));
                        roleInfo.setRoleLevel(orderInfoObj.getString("roleLevel"));
                        roleInfo.setVipLevel("0");

                        orderInfo = new PayParams(orderInfoObj.getString("outTradeNo"),new BigDecimal(orderInfoObj.getString("amount")),
                                roleInfo.getServerId(),
                                roleInfo.getServerName(),
                                roleInfo.getRoleId(),
                                roleInfo.getRoleName(),
                                orderInfoObj.getString("propsName"));
                        orderInfo.setGoodsId(orderInfoObj.getString("goodsId"));
                    } catch (JSONException e) {
                        e.printStackTrace();
                    }
                    BZPay.getInstance().pay(GameActivity.this, orderInfo, roleInfo);
                }
            });
        } catch (Exception e) {
            CommonUtil.printThrowableInfo(e);
        }
    }

    public void exit() {
        try {
            runOnUiThread(new Runnable() {
                /* class com.qk.plugin.js.shell.MainActivity.AnonymousClass15 */

                @Override // java.lang.Runnable
                public void run() {
                    Log.d(GameActivity.TAG, "do exit");
                    if (BZUser.getInstance().isSupport(Constants.METHOD_EXIT)) {
                        BZUser.getInstance().exit(GameActivity.this);
                    } else {
                        new AlertDialog.Builder(GameActivity.this).setTitle("退出").setMessage("是否退出游戏?").setPositiveButton("确定", new DialogInterface.OnClickListener() {
                            /* class com.qk.plugin.js.shell.MainActivity.AnonymousClass15.AnonymousClass1 */

                            @Override // android.content.DialogInterface.OnClickListener
                            public void onClick(DialogInterface arg0, int arg1) {
                                BZUser.getInstance().exit(GameActivity.this);
                            }
                        }).setNegativeButton("取消", (DialogInterface.OnClickListener) null).show();
                    }
                }
            });
        } catch (Exception e) {
            CommonUtil.printThrowableInfo(e);
        }
    }

    public void bzSetGameRoleInfo(String serverId, String serverName, String roleId, String roleName, String roleLevel, String vipLevel, String balance, String partyName,  String partyId, String roleGender, String rolePower, String partyRoleId, String partyRoleName, String professionId, String profession) {
        UserExtraData roleInfo = new UserExtraData();
        roleInfo.setServerId(serverId);
        roleInfo.setServerName(serverName);
        roleInfo.setRoleId(roleId);
        roleInfo.setRoleName(roleName);
        roleInfo.setRoleLevel(roleLevel);
        roleInfo.setVipLevel(vipLevel);
        roleInfo.setAmount(new BigDecimal(balance));
        roleInfo.setPartyName(partyName);
        roleInfo.setPartyId(partyId);
        roleInfo.setRoleGender(roleGender);
        roleInfo.setRolePower(rolePower);
        roleInfo.setPartyRoleId(partyRoleId);
        roleInfo.setPartyRoleName(partyRoleName);
        roleInfo.setProfessionId(professionId);
        roleInfo.setProfessionName(profession);
        BZUser.getInstance().submitExtraData(GameActivity.this, roleInfo);
    }

    public class BZHDJsInterface {
        BZHDJsInterface() {
        }

        @JavascriptInterface
        public void callAndroidFunction(String json) {
            Log.d(GameActivity.TAG, "callAndroidFunction　jsonData:" + json);
            try {
                JSONObject jObject = new JSONObject(json);
                JSONObject jsonData = new JSONObject(jObject.getString("data"));
                String action = jObject.optString("action");
                if (action.equalsIgnoreCase(Constant.JS_ACTION_WEB_LOADED)) {
                    JSONObject jsonObject = new JSONObject();
                    try {
                        jsonObject.put("action", "setBZHDData");
                        JSONObject dataJsonObject = new JSONObject();
                        dataJsonObject.put("status", true);
                        dataJsonObject.put("appid",AppConfig.appid);
                        dataJsonObject.put("appkey",AppConfig.appkey);
                        dataJsonObject.put("channelGameCode",BZSDK.getInstance().getCurrChannel2());
                        Log.d(GameActivity.TAG, "init success channel_type:" + BZSDK.getInstance().getCurrChannel2());
                        jsonObject.put("data", dataJsonObject);
                    } catch (Exception e3) {
                        CommonUtil.printThrowableInfo(e3);
                    }
                    GameActivity.this.callJsFunc(jsonObject);
                } else if (action.equalsIgnoreCase(Constant.JS_ACTION_LOGIN)) {
                    if (GameActivity.this.mIniting.booleanValue()) {
                        Log.d(GameActivity.TAG, "callAndroidFunction　login...initing...return");
                        GameActivity.this.mNeedRetryLogin = true;
                    } else if (GameActivity.this.mInitFinished.booleanValue()) {
                        Log.d(GameActivity.TAG, "callAndroidFunction　login");
                        GameActivity.this.mNeedRetryLogin = false;
                        GameActivity.this.login();
                    } else {
                        Log.d(GameActivity.TAG, "callAndroidFunction　login...do init and retry login");
                        GameActivity.this.mNeedRetryLogin = true;
                        GameActivity.this.init();
                    }
                } else if (action.equalsIgnoreCase(Constant.JS_ACTION_LOGOUT)) {
                    GameActivity.this.logout();
                } else if (action.equalsIgnoreCase(Constant.JS_ACTION_UPDATE_ROLE)) {
                    GameActivity.this.setGameRoleInfo(jsonData);
                } else if (action.equalsIgnoreCase(Constant.JS_ACTION_PAY)) {
                    Log.e(GameActivity.TAG, "jsonData=" + jsonData);
                    GameActivity.this.pay(jsonData);
                } else if (action.equalsIgnoreCase(Constant.JS_ACTION_EXIT)) {
                    GameActivity.this.exit();
                } else if (action.equalsIgnoreCase(Constant.JS_ACTION_EXTEND)) {
                    Log.e(GameActivity.TAG, "JS_ACTION_EXTEND");
                    String key = jsonData.optString("key");
                    String callbackFun = jsonData.optString("callbackFun");
                    Log.d(GameActivity.TAG, "key: " + key);
                    Log.d(GameActivity.TAG, "callbackFun: " + callbackFun);
                    if (key.equals("getScreenForVivo")) {
                        GameActivity.this.callJsFunc(GameActivity.this.getScreenForVivo(), callbackFun);
                    } else if (key.equals("getScreenType")) {
                        GameActivity.this.callJsFunc(GameActivity.this.getScreenType(), callbackFun);
                    }
                }
            } catch (JSONException e4) {
                CommonUtil.printThrowableInfo(e4);
            }
        }
    }

    @Override
    public void onBackPressed() {
        exit();
    }

    private void callJsFunc(final JSONObject jsonObject) {
        try {
            Log.d(TAG, "callJsFunc");
            this.mGameWebView.post(new Runnable() {
                /* class com.qk.plugin.js.shell.MainActivity.AnonymousClass16 */

                @Override // java.lang.Runnable
                public void run() {
                    GameActivity.this.mGameWebView.loadUrl("javascript:CallbackFromAndroid('" + jsonObject.toString() + "')");
                }
            });
        } catch (Exception e) {
            Log.e(TAG, "调用JS方法出现异常：" + e.toString());
            CommonUtil.printThrowableInfo(e);
        }
    }


    private void callJsFunc(final JSONObject jsonObject, final String methodName) {
        try {
            Log.d(TAG, "callJsFunc: " + methodName);
            this.mGameWebView.post(new Runnable() {
                /* class com.qk.plugin.js.shell.MainActivity.AnonymousClass17 */

                @Override // java.lang.Runnable
                public void run() {
                    GameActivity.this.mGameWebView.loadUrl("javascript:" + methodName + "('" + jsonObject.toString() + "')");
                }
            });
        } catch (Exception e) {
            Log.e(TAG, "调用JS方法出现异常：" + e.toString());
            CommonUtil.printThrowableInfo(e);
        }
    }

    public void setHideVirtualKey(Window window) {
        int uiOptions;
        if (Build.VERSION.SDK_INT >= 19) {
            uiOptions = 1798 | 4096;
        } else {
            uiOptions = 1798 | 1;
        }
        window.getDecorView().setSystemUiVisibility(uiOptions);
    }

    public JSONObject getScreenForVivo() {
        JSONObject dataJsonObject2 = new JSONObject();

        boolean isVivoAoCao = isVivoFeatureSupport(32, this);
        boolean isVivoCircle = isVivoFeatureSupport(8, this);
        try {
            dataJsonObject2.put("vivo_aojiao", String.valueOf(isVivoAoCao));
            dataJsonObject2.put("vivo_yuanjiao", String.valueOf(isVivoCircle));
            return dataJsonObject2;
        } catch (JSONException e) {
            e.printStackTrace();
            return dataJsonObject2;
        }
    }

    public JSONObject getScreenType() {
        JSONObject dataJsonObject2 = new JSONObject();
        try {
            dataJsonObject2.put("screenType", String.valueOf(RomUtil.hasNotchScreen(this)));
        } catch (JSONException e) {
            e.printStackTrace();
        }
        return dataJsonObject2;
    }



    private static boolean isVivoFeatureSupport(int mask, Context context) {
        try {
            Class<?> ftFeatureClass = context.getClassLoader().loadClass("android.util.FtFeature");
            return ((Boolean) ftFeatureClass.getMethod("isFeatureSupport", Integer.TYPE).invoke(ftFeatureClass, Integer.valueOf(mask))).booleanValue();
        } catch (Exception e) {
            return false;
        }
    }
}